package me.chyxion.spring.ext.codegen.services.support;

import java.io.File;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import me.chyxion.spring.ext.codegen.services.CodeGenerator;

/**
 * @version 0.0.2
 * @since 0.0.1
 * @author Shaun Chyxion <br />
 * chyxion@163.com <br />
 * Oct 7, 2014 12:23:13 PM
 */
@Service
@Order(Ordered.LOWEST_PRECEDENCE)
public class TableCodeGen extends CodeGenerator {
	private static final Logger log = LoggerFactory.getLogger(TableCodeGen.class);

	/*
	 * (non-Javadoc)
	 * @see me.chyxion.spring.ext.codegen.services.CodeGenerator#process(java.util.Map, java.lang.String, java.lang.String)
	 */
    @Override
    public String process(Map<String, Object> dataModel, String module, String model) {
    	String table = (String) dataModel.get("table");
    	log.info("Process Generate Table [{}] SQL File.", table);
    	StringBuilder filePath = new StringBuilder(resourcesDir)
    		.append("db/");
    	if (StringUtils.isNotBlank(module)) {
    		filePath.append(module).append("/");
    	}
    	filePath.append(table).append(".sql");
    	render(filePath, "/codegen/table.ftl", dataModel);
    	if (!Boolean.FALSE.equals(dataModel.get("createTable"))) {
			// ignore drop table error
			try {
				log.info("Execute Drop Table [{}].", table);
				baseTool.execSQL("drop table " + table);
			}
			catch (Exception e) {
				log.info("Drop Table Failed, Error Message [{}], Ingore.",
						e.getMessage());
			}
			// ignore execute sql error
			try {
				log.info("Execut Create Table SQL File [{}].", filePath);
				baseTool.execSQL(new File(baseTool.getProjDir(), filePath
						.toString()));
			}
			catch (Exception e) {
				log.warn("Database Create Table Error, Ingore.", e);
			}
    	}
    	return filePath.toString();
    }
}
